package 力扣;

/**
 * @author yyq
 * @create 2022-04-09 16:31
 */
public class leetcode110 {
    public boolean isBalanced(TreeNode root) {
        int height = getHeight(root);
        if(height==-1) return false;
        else return true;
    }

    public int getHeight(TreeNode root){
        if(root==null) return 0;
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }
        if(Math.abs(leftHeight-rightHeight) >1) return -1;
        return Math.max(leftHeight,rightHeight) + 1;
    }

    private void preOrderBalace(TreeNode root, int[] flag) {

        int leftDepth = 0;
        int rightDepth = 0;
        if(root.left!=null) leftDepth = maxDepth(root.left);
        if(root.right!=null) rightDepth = maxDepth(root.right);
        if(leftDepth - rightDepth>=2 || rightDepth - leftDepth>=2){
            flag[0] = 0;
            return;
        }

        if(root.left!=null)
        preOrderBalace(root.left,flag);
        if(root.right!=null)
        preOrderBalace(root.right,flag);

    }

    public static int maxDepth(TreeNode root){
        int[] max=new int[1];
        max[0]=0;
        int temp=0;
        if(root==null) return max[0];
        preOrder(temp,max,root);
        return max[0];
    }

    private static int preOrder(int temp, int[] max, TreeNode root) {
        temp++;
        if (temp>max[0]) max[0]=temp;
        if(root.left!=null) {
            temp = preOrder(temp,max,root.left);
            temp--;
        }
        if(root.right!=null){
            temp = preOrder(temp,max,root.right);
            temp--;
        }
        return temp;

    }
}
